package com.egao.gps.quartz;

import com.egao.common.core.config.WebSocketServer;
import com.egao.common.core.damon.utils.CacheUtils;
import com.egao.common.core.damon.utils.StringUtil;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.system.entity.User;
import com.egao.gps.ZjxlGps;
import com.egao.gps.entity.CarPosition;
import com.egao.gps.service.CarPositionService;
import com.egao.gps.utils.DistanceUtil;
import com.egao.orderB.biz.AddressFactoryBiz;
import com.egao.orderB.biz.BillProcessBiz;
import com.egao.orderB.biz.ElectricFenceBiz;
import com.egao.orderB.entity.AddressFactory;
import com.egao.orderB.entity.Bill;
import com.egao.orderB.entity.BillProcess;
import com.egao.orderB.entity.ElectricFence;
import com.egao.orderB.service.BillService;
import net.sf.json.JSONArray;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Doman
 * @version ：1.0
 * @date : 2020-02-07 14:04
 */
public class JKXScheduledJob implements Job {

    @Autowired
    private CarPositionService carPositionService;
    @Autowired
    private BillService billService;
    @Autowired
    private BillProcessBiz billProcessBiz;
    @Autowired
    private ElectricFenceBiz electricFenceBiz;
    @Autowired
    private AddressFactoryBiz addressFactoryBiz;

    private String name;

    public void setName(String name) {
        this.name = name;
    }


//    public static void main(String[] args) {
//        System.out.println(11);
//        CarPosition c = new CarPosition();
//        c.setBillId("12");
//        c.setWarn(11);
//
//        CarPosition aa = (CarPosition) c.clone();
//        System.out.println(11);
//    }
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        List<Bill> list = billService.list(null);
//        for (int i=0; i < list.size(); i ++) {
//            CarPosition carPosition = ZjxlGps.vLastLocationV3(list.get(i).getVno());
//            if (Utils.isNotEmpty(carPosition)) {
//                carPositionService.save(carPosition);
//            }
//        }
        User adminuser = new User(1,1);
        List<Bill> bills = billService.findCarName(null);
        String[] strs2 = {"",""};
        if(bills != null && bills.size()>0) {
            for (Bill b: bills) {
                strs2[0] += b.getCarNo()+"_2,";
                strs2[1] += b.getId()+",";
            }
            strs2[0] = strs2[0].substring(0,strs2[0].length()-1);
            strs2[1] = strs2[1].substring(0,strs2[1].length()-1);
            try {
                List<CarPosition> carPositions = ZjxlGps.vLastLocationV4(strs2[0],strs2[1]);

//                List<CarPosition> carPositions = new ArrayList<>();
//                CarPosition carPosition = new CarPosition();
//                carPosition.setId(ObjectId.get());
//                carPosition.setVno("浙BJ8510");
//                carPosition.setBillId("3696");
//                carPosition.setLon("121.636309");
//                carPosition.setLat("29.842781");
//                carPosition.setVco("2");
//                carPosition.setAdr("22222");
//                carPosition.setSpd("22");
//                carPosition.setProvince("a");
//                carPosition.setCity("b");
//                carPosition.setCountry("c");
//                carPosition.setDrc("d");
//                carPosition.setUtc(DateUtil.getCurrentDate());
//                carPosition.setCreateDate(DateUtil.getCurrentDate());
//                carPositions.add(carPosition);

                if (carPositions != null && carPositions.size() > 0) {
                    List<CarPosition> carPositions_copy = new ArrayList<>();
                    for (CarPosition cp: carPositions) {
                        try {
                            boolean stateRet = false;
                            for (Bill btemp: bills) {
                                if(btemp.getId().equals(cp.getBillId())
                                        && !btemp.getState().equals("已做单")) {
                                    stateRet = true;
                                    break;
                                }
                            }
                            //已做单的轨迹不要放到mongodb里
                            if(stateRet) {
                                carPositions_copy.add(cp);
                            }
                        } catch (Exception e) {}
                    }
                    carPositionService.saveBatch(carPositions_copy);

                    //------------
                    //实时轨迹不用刷新
                    List<CarPosition> carPositions_sync = new ArrayList<>();
                    for (CarPosition c : carPositions) {
                        CarPosition c2 = c.clone();
                        for (Bill b: bills) {
                            if(c2.getBillId().equals(b.getId())) {
                                AddressFactory addressFactory = new AddressFactory();
                                addressFactory.setBillId(b.getId());
                                List<AddressFactory> addressFactories = addressFactoryBiz.list(addressFactory, new User(1));
                                String add = "";

                                if (Utils.isNotEmpty(addressFactories)) {
                                    AddressFactory af = addressFactories.get(0);
                                    add = af.getFaddress();
//                                    if (StringUtil.isBlank(af.getLongitude(), af.getLatitude()) || af.getLongitude().equals("null") ||af.getLatitude().equals("null")) {
//                                        break;
//                                    }
                                }
//                                if (StringUtil.isBlank(b.getUpYardLongitude(), b.getUpYardLatitude()) || b.getUpYardLongitude().equals("null") ||b.getUpYardLatitude().equals("null")) {
//                                    break;
//                                }
                                /*int red = 0,distance = 0,duration = 0;
                                String nine = DateUtil.getCurrentDate("yyyy-MM-dd")+" 09:30:00";
                                int ret = DateUtil.compareToDate(b.getPackDate(),nine,"yyyy-MM-dd hh:mm:ss");
                                if(ret <= 0) {
                                    if (b.getState().equals("已提箱")) {
//                                System.out.println("mapResult11:"+b.getUpYardLongitude()+"=" + b.getUpYardLatitude()+"=="+addLL);
                                        MapNavUtil mapResult=new MapNavUtil(b.getUpYardLongitude()+"," + b.getUpYardLatitude(), addLL, UserConstant.GAODE_MAP_KEY);
//                                System.out.println("mapResult22:"+mapResult.getResults().toString());
                                        distance = Integer.valueOf(mapResult.getResults().getDistance());
                                        duration = Integer.valueOf(mapResult.getResults().getDuration());
                                        Date arriver = DateUtil.addDatePlusMin(DateUtil.parseDate(DateUtil.getCurrentDate()), duration/60 + 60);
                                        if (DateUtil.compareToDate(arriver, DateUtil.parseDate(b.getPackDate())) > 0) {
                                            red = 1;
                                        }
                                        c2.setDuration(DateUtil.formatDate(DateUtil.addDatePlusMin(DateUtil.parseDate(DateUtil.getCurrentDate()), duration/60)));
                                        c2.setDistance(new BigDecimal(distance / 1000.0).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+"");
                                    } else if (b.getState().equals("已做单")){
                                        red = 2;
                                    }
                                }
                                c2.setWarn(red);*/
                                c2.setDriver(b.getDriver());
                                c2.setDriverPhone(b.getDriverPhone());
                                c2.setBillOfLading(b.getBillOfLading());
                                c2.setCustomer(b.getCustomer());
                                c2.setCarTeam(b.getCarTeam());
                                c2.setFactoryAddress(add);
                                c2.setAddressFactoryList(addressFactories);
                                c2.setAddress(b.getAddress());
                                c2.setUpyard(b.getUpYard());
                                c2.setUpyardLongitude(b.getUpYardLongitude());
                                c2.setUpyardLatitude(b.getUpYardLatitude());
                                c2.setDock(b.getDock());
                                c2.setDockLongitude(b.getDockLongitude());
                                c2.setDockLatitude(b.getDockLatitude());
                                c2.setState(b.getState());
                                c2.setPackDate(b.getPackDate());
                                carPositions_sync.add(c2);
                                break;
                            }
                        }

                    }
                    WebSocketServer.sendInfo(JSONArray.fromObject(carPositions_sync).toString(),"indexGps");
                    //------------------

                    for (CarPosition cp: carPositions) {
                        //得到订单状态
                        List<Bill> btemps = bills.stream().filter(s -> s.getId().equals(cp.getBillId())).collect(Collectors.toList());
                        Bill btemp = btemps.get(0);
                        if(StringUtil.isBlank(btemp.getEfDock(),btemp.getEfYard())){
                            continue;
                        }
                        List<String> yardDockIds = new ArrayList<>();
                        if(Utils.isNotEmpty(btemp.getEfDock())) {
                            yardDockIds.add(btemp.getEfDock());
                        }
                        if(Utils.isNotEmpty(btemp.getEfYard())) {
                            yardDockIds.add(btemp.getEfYard());
                        }
//                        System.out.println("factoryIds"+btemp.getEfFactoryAddress()+"btemp.getEfDock()"+btemp.getEfDock()+"btemp.getEfYard()"+btemp.getEfYard());
                        ElectricFence ef2 = new ElectricFence();
                        ef2.setYardDockIds(yardDockIds);
                        ef2.setBillId(btemp.getId());

                        if(yardDockIds == null || yardDockIds.size()==0){continue;}
//                        List<ElectricFence> efs = electricFenceBiz.list(ef2, adminuser);
                        List<ElectricFence> efs = electricFenceBiz.factoryYardDockEfs(ef2);
                        if(efs ==null || efs.size() == 0){continue;}


                        /*BillProcess bp = new BillProcess();
                        bp.setBillId(btemp.getId());
                        List<BillProcess> bpList = billProcessBiz.list(bp);
                        bp = bpList.get(0);
                        boolean drop = false;
                        for (BillProcess billp : bpList) {
                            if(billp.getState().equals("落箱")){
                                drop = true;
                                break;
                            }
                        }
                        if(drop){ continue; }
                        */
                        try {
//                            double[] gps = DistanceUtil.toGD(cp.getLon() + "," + cp.getLat());
                            double[] gps = DistanceUtil.toTX(cp.getLat() + "," + cp.getLon());
//                            double[] gps = TxLngLonUtil.gps84_To_Gcj02(Double.valueOf(cp.getLat()), Double.valueOf(cp.getLon()));
                            if(btemp.getState().equals("已提箱")) {
                                efs.stream()
                                .filter((p) -> (p.getType().equals("工厂")))
                                .forEach((eft) -> {
                                    double m = DistanceUtil.getDistance(gps[0],gps[1],
                                            Double.valueOf(eft.getLongitude()),
                                            Double.valueOf(eft.getLatitude()));
                                    if(m <= Double.parseDouble(eft.getRadius())) {
                                        btemp.setRemark(eft.getName());

                                        billService.arrivedFactory(btemp,adminuser);
                                    }
                                });
                            } else if(btemp.getState().equals("已到厂")) {
                                BillProcess bp = new BillProcess();
                                bp.setBillId(btemp.getId());
                                List<BillProcess> bpList = billProcessBiz.list(bp);
                                bp = bpList.get(0);
                                for (ElectricFence eft: efs) {
                                    if(eft.getType().equals("工厂")) {
                                        if(bp.getRemark().equals(eft.getName())){
                                            double m = DistanceUtil.getDistance(gps[0],gps[1],
                                                    Double.valueOf(eft.getLongitude()),
                                                    Double.valueOf(eft.getLatitude()));
//                                            if(m > Double.parseDouble(eft.getRadius())) {
                                            if(m > 3000) {
                                                btemp.setRemark(eft.getName());
                                                billService.leaveFactory(btemp,adminuser);
                                            }
                                        }
                                    }
                                }
                            } else if(btemp.getState().equals("已离厂")) {
                                boolean cret = true;
                                BillProcess bp = new BillProcess();
                                bp.setBillId(btemp.getId());
                                List<BillProcess> bpList = billProcessBiz.list(bp);
                                bp = bpList.get(0);
                                for (ElectricFence eft: efs) {
                                    if(eft.getType().equals("工厂")) {
                                        if(Utils.isNotEmpty(bp.getRemark()) && !bp.getRemark().equals(eft.getName())) {
                                            double m = DistanceUtil.getDistance(gps[0], gps[1],
                                                    Double.valueOf(eft.getLongitude()),
                                                    Double.valueOf(eft.getLatitude()));
                                            if (m <= Double.parseDouble(eft.getRadius())) {
                                                btemp.setRemark(eft.getName());
                                                billService.arrivedFactory(btemp, adminuser);
                                                cret = false;
                                            }
                                        }
                                    }
                                }
                                if(cret) {
                                    for (ElectricFence eft: efs) {
                                        if(eft.getType().equals("港口")) {
                                            double m = DistanceUtil.getDistance(gps[0],gps[1],
                                                    Double.valueOf(eft.getLongitude()),
                                                    Double.valueOf(eft.getLatitude()));
                                            if(m <= Double.parseDouble(eft.getRadius())) {
                                                btemp.setRemark(eft.getName());
                                                billService.inPort_gps(btemp,adminuser);
                                            }
                                        }
                                    }
                                }
                            } else {
                                efs.stream()
                                .filter((p) -> (p.getType().equals("堆场")))
                                .forEach((eft) -> {
                                    double m = DistanceUtil.getDistance(gps[0],gps[1],
                                            Double.valueOf(eft.getLongitude()),
                                            Double.valueOf(eft.getLatitude()));
                                    if(m <= Double.parseDouble(eft.getRadius())) {
                                        CacheUtils.timedCacheOutEF.put(btemp.getBillOfLading()+btemp.getId()+"dc","1");
                                    } else if(CacheUtils.timedCacheOutEF.get(btemp.getBillOfLading()+btemp.getId()+"dc").equals("1")){
                                        CacheUtils.timedCacheOutEF.put(btemp.getBillOfLading()+btemp.getId()+"dc","2");
                                        btemp.setRemark(eft.getName());
                                        billService.upBox_gps(btemp,adminuser);
                                    }
                                });
                            }
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//        System.out.println("CRON ----> schedule zjxl is running ... + " + name + "  ---->  " + DateUtil.getCurrentDate());
    }

//    public static void main(String[] args) throws InterruptedException {
//        CacheUtils.timedCacheOutEF.put("11","112");
//        CacheUtils.timedCacheOutEF.put("22","33",2000);
//        CacheUtils.timedCacheOutEF.put("44","44",4000);
//        Thread.sleep(3000);
//        System.out.println(CacheUtils.timedCacheOutEF.get("11"));
//        System.out.println(CacheUtils.timedCacheOutEF.get("22"));
//        System.out.println(CacheUtils.timedCacheOutEF.get("44"));
//        System.out.println(CacheUtils.timedCacheOutEF.get("11").equals("1221"));
//    }

}